package Demo92;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 腐烂的橘子
 * https://leetcode.cn/problems/2bCMpM/submissions/564419832/
 */
class Solution {
    int m,n;
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    public int orangesRotting(int[][] grid) {
        m = grid.length; n = grid[0].length;
        Queue<int[]> q = new LinkedList<>();
        boolean[][] vis = new boolean[m][n];

        int huai = 0, hao = 0;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 2) {
                    q.add(new int[] {i,j});
                    vis[i][j] = true;
                }
                if(grid[i][j] == 1) {
                    hao++;
                }
            }
        }
        if(hao == 0) return 0;
        int stap = 0;
        while(!q.isEmpty()) {
            stap++;
            int sz = q.size();
            while(sz-- != 0) {
                int[] t = q.poll();
                int a = t[0], b = t[1];
                for(int i = 0; i < 4; i++) {
                    int x = a + dx[i], y = b + dy[i];
                    if(x >= 0 && x < m && y >= 0 && y < n && !vis[x][y]) {
                        if(grid[x][y] == 1) {
                            hao--;
                            q.add(new int[] {x,y});
                        }
                        vis[x][y] = true;
                        if(hao == 0) return stap;
                    }
                }
            }
        }
        return -1;
    }
}